import { NextResponse } from "next/server";
import connect from "@/utils/mongodb";
import User from "@/model/User";
import bcrypt from "bcryptjs";
import { getServerSession } from "next-auth/next";
import { authOptions } from "../[...nextauth]/route";

// 验证密码强度
const isPasswordStrong = (password) => {
    // 至少8位，包含大小写字母、数字和特殊字符
    const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/;
    return regex.test(password);
};

export async function POST(request) {
    try {
        // 1. 验证用户登录状态
        const session = await getServerSession(authOptions);
        if (!session || !session.user) {
            return NextResponse.json(
                { error: "请先登录" },
                { status: 401 }
            );
        }

        // 2. 解析请求数据
        const { oldPassword, newPassword, confirmPassword } = await request.json();

        // 3. 基础校验
        if (!oldPassword || !newPassword || !confirmPassword) {
            return NextResponse.json(
                { error: "请填写所有字段" },
                { status: 400 }
            );
        }

        if (newPassword !== confirmPassword) {
            return NextResponse.json(
                { error: "两次输入的新密码不一致" },
                { status: 400 }
            );
        }

        if (newPassword === oldPassword) {
            return NextResponse.json(
                { error: "新密码不能与旧密码相同" },
                { status: 400 }
            );
        }

        // 4. 密码强度校验
        if (!isPasswordStrong(newPassword)) {
            return NextResponse.json(
                {
                    error: "新密码强度不足：至少8位，包含大小写字母、数字和特殊字符"
                },
                { status: 400 }
            );
        }

        // 5. 连接数据库并验证旧密码
        await connect();
        const user = await User.findById(session.user.id);
        if (!user) {
            return NextResponse.json(
                { error: "用户不存在" },
                { status: 404 }
            );
        }

        // 验证旧密码是否正确
        const isOldPasswordValid = await bcrypt.compare(oldPassword, user.password);
        if (!isOldPasswordValid) {
            return NextResponse.json(
                { error: "旧密码不正确" },
                { status: 400 }
            );
        }

        // 6. 更新密码
        const hashedNewPassword = await bcrypt.hash(newPassword, 10);
        user.password = hashedNewPassword;
        await user.save();

        return NextResponse.json({
            message: "密码修改成功，请重新登录",
            success: true
        });

    } catch (error) {
        console.error("修改密码接口错误:", error);
        return NextResponse.json(
            { error: "修改密码失败，请稍后再试" },
            { status: 500 }
        );
    }
}